package com.tongfusoft.web.core.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import ognl.Ognl;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.utils.Logger;
import com.tongfusoft.utils.web.WebUtils;
import com.tongfusoft.web.core.Constant;
import com.tongfusoft.web.core.data.BaseData;
import com.tongfusoft.web.core.data.User;
import com.tongfusoft.web.core.service.ILogService;
import com.tongfusoft.web.utils.DataBeanDetector;

/**
 * 所有Action的基类，提供了一些常用输出的基本方法和request、response、session的获取
 * 
 * @author shadow guo
 * 
 */
public class BaseAction extends ActionSupport implements BeanFactoryAware {
	private static final Log logger = LogFactory.getLog(BaseAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String characterEncoding = "UTF-8";
	protected BeanFactory beanFactory;
	private String actionCode;
	private ILogService logService;
	
	public ILogService getLogService() {
		return logService;
	}

	public void setLogService(ILogService logService) {
		this.logService = logService;
	}

	public String getCharacterEncoding() {
		return characterEncoding;
	}

	public void setCharacterEncoding(String characterEncoding) {
		this.characterEncoding = characterEncoding;
	}

	public String getActionCode() {
		return actionCode;
	}

	public void setActionCode(String actionCode) {
		this.actionCode = actionCode;
	}

	/**
	 * 输出JSON格式的文本
	 * 
	 * @param str
	 */
	protected void outJsonString(String str) {
		getResponse().setContentType(
				"text/javascript;charset=" + this.getCharacterEncoding());
		outString(str);
	}

	/**
	 * 输出JSON格式的文本
	 * 
	 * @param obj
	 */
	protected void outJson(Object obj) {
		if (obj instanceof List || obj.getClass().isArray()) {
			outJsonArray(obj);
		} else {

			outJsonString(JSONObject.fromObject(obj).toString());
		}
	}

	/**
	 * 输出JSON格式的文本
	 * 
	 * @param array
	 */
	protected void outJsonArray(Object array) {
		outJsonString(JSONArray.fromObject(array).toString());
	}

	/**
	 * 输出文本
	 * 
	 * @param str
	 */
	protected void outString(String str) {
		try {
			PrintWriter out = getResponse().getWriter();
			LOG.debug(str);
			out.write(str);
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
	}

	/**
	 * 输出XML
	 * 
	 * @param xmlStr
	 */
	protected void outXMLString(String xmlStr) {
		getResponse().setContentType(
				"application/xml;charset=" + this.getCharacterEncoding());
		outString(xmlStr);
	}

	/**
	 * 获取HttpServletRequest
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获取HttpServletResponse
	 * 
	 * @return
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 获取HttpSession
	 * 
	 * @return
	 */
	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 获取ServletContext
	 * 
	 * @return
	 */
	protected ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}

	/**
	 * 获得Web应用的完整根目录URL
	 * 
	 * @return
	 */
	protected String getServerUrlPath() {
		return WebUtils.getServerUrlPath(getRequest());
	}

	/**
	 * 获得Web应用的物理根目录
	 * 
	 * @param request
	 * @return
	 */
	protected String getServerPath() {
		return WebUtils.getRealServerPath(getRequest());
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	/**
	 * 获取inpustream内容
	 * 
	 * @return
	 * @throws IOException
	 */
	protected String getInputStr() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				getRequest().getInputStream(), "UTF-8"));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}

		return sb.toString();
	}

	/**
	 * 从session获取当前用户对象
	 * @return
	 */
	protected User getCurrUser() {
		return (User) ServletActionContext.getContext().getSession()
				.get(Constant.SESSION_USER);
	}

	/**
	 * 获取request中某个参数
	 * @param name
	 * @return
	 */
	protected Object getParamByName(String name) {
		Object[] obs = (Object[]) ServletActionContext.getContext()
				.getParameters().get(name);
		if (obs != null && obs.length == 1) {
			return obs[0];
		} else {
			return obs;
		}
	}

	/**
	 * 获取所有request参数，返回Map对象
	 * @return
	 */
	protected Map getRequestParameters() {
		Iterator<String> keys = ServletActionContext.getContext()
				.getParameters().keySet().iterator();
		Map result = new HashMap();
		while (keys.hasNext()) {
			String key = keys.next();
			result.put(key, this.getParamByName(key));
		}

		return result;
	}

	/**
	 * 获取request和session中所有参数，返回Map对象
	 * @return
	 */
	protected Map getRequesAndSessiontMap(){
		Map param = getRequestParameters();
		param.putAll(ServletActionContext.getContext().getSession());
		
		return param;
	}
	
	/**
	 * 获取request、session、application中所有参数，返回Map对象
	 * @return
	 */
	protected Map getAllParamMap(){
		Map param = getRequestParameters();
		param.putAll(ServletActionContext.getContext().getSession());
		param.putAll(ServletActionContext.getContext().getApplication());
		
		return param;
	}
	
	/**
	 * 获取BaseData的定义
	 * @param params
	 * @return
	 */
	protected BaseData getDataDefine(String beanName){
		if(StringUtils.isNotEmpty(beanName)){
			String className = DataBeanDetector.getDataBeanName(beanName);
			Logger.debug("bean name:" + className);
			if(StringUtils.isNotEmpty(className)){
				try {
					BaseData bd = (BaseData)Class.forName(className).newInstance();
					
					return bd;
				} catch (Exception e) {
					throw new ServiceException(e);
				}
			}else{
				throw new ServiceException("convert error,not found matching bean:" + className); 
			}
		}else{
			throw new ServiceException("convert error,not found beanName");
		}
	}
	
	/**
	 * 对Ognl的设置值进行处理
	 * @param params
	 * @return
	 */
	protected Map convertMap(Map params){
		//
		Map map = new HashMap();
		map.putAll(params);
		
		Iterator<String> keys = params.keySet().iterator();
		while(keys.hasNext()){
			String key = keys.next();
			if(params.get(key) instanceof String && StringUtils.startsWith((String)params.get(key),"el:")){
				//进行ognl的处理,处理session中所有值
				Map sessionMap = ActionContext.getContext().getSession();
				try{
					String expression = (String)params.get(key);
					expression = expression.substring(3);
					
					map.put(key,Ognl.getValue(expression, sessionMap));
				}catch(Exception e){
					logger.error("ognl parser error:" + e.getMessage());
				}
			}else{
				map.put(key, params.get(key));
			}
		}
		
		return map;
	}
}
